package com.wentao.thisService.common;

import com.wentao.thisCommon.model.RequestBase;
import com.wentao.thisCommon.model.ResultBase;
import com.wentao.thisFacade.common.enums.ExceptionCode;
import com.wentao.thisService.service.AuthenticationService;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description: 验证令牌
 * @Author: ZhaiYanTao
 * @Date: 2020/3/6 18:12
 */
@Aspect
@Component
public class TokenVerifyAop {

    // TODO: 2020/3/27 验证逻辑修改 redis
    @Autowired
    private AuthenticationService authenticationService;

    @Pointcut("@annotation(com.wentao.thisService.common.TokenVerify)")
    public void tokenCheck() {
    }

    @Around("tokenCheck()&&@annotation(tokenVerify)")
    public Object check(ProceedingJoinPoint joinPoint, TokenVerify tokenVerify) throws Throwable {
        Object[] args = joinPoint.getArgs();

        RequestBase requestBase = (RequestBase) args[0];
        String userIdString = requestBase.getUserId();
        Long userId = null;
        if (StringUtils.isNotBlank(userIdString)) {
            userId = Long.parseLong(userIdString);
        }
        String token = requestBase.getToken();

        if (null == userId) {
            return ResultBase.ok(ExceptionCode.USERID_EMPTY_ERROR);
        }
        if (StringUtils.isBlank(token)) {
            return ResultBase.ok(ExceptionCode.TOKEN_EMPTY_ERROR);
        }
        // TODO: 2020/3/28 验证逻辑好好捋一捋！
        boolean checkLoginFlag = authenticationService.checkLogin(userId, token);
        if (checkLoginFlag) {
            return joinPoint.proceed();
        } else {
            return ResultBase.ok(ExceptionCode.AUTHORITY_ERROR);
        }

    }
}
